﻿using Shop.Model.UserGrade;
using Shop.Repository;
using WeDonekRpc.CacheClient.Interface;
using WeDonekRpc.Helper;

namespace Shop.Collect.lmpl
{
    internal class UserGradeCollect : IUserGradeCollect
    {
        private static readonly string _CacheKey = "UserGrade";
        private readonly IUserGradeRepository _Repository;
        private readonly ICacheController _Cache;

        public UserGradeCollect (IUserGradeRepository repository, ICacheController cache)
        {
            this._Repository = repository;
            this._Cache = cache;
        }

        public long GetGradeId (long integral)
        {
            GradeBase[] grades = this.GetGrades();
            return grades.Where(c => c.Integral <= integral).OrderByDescending(a => a.Sort).Select(a => a.Id).FirstOrDefault();
        }
        public GradeBase[] GetGrades ()
        {
            if (this._Cache.TryGet(_CacheKey, out GradeBase[] list))
            {
                return list;
            }
            list = this._Repository.GetAll<GradeBase>("Sort");
            _ = this._Cache.Add(_CacheKey, list);
            return list;
        }
        public string GetName (long id)
        {
            return this._Repository.Get(id, a => a.GradeName);
        }
        public Dictionary<long, string> GetName (long[] ids)
        {
            if (ids.IsNull())
            {
                return null;
            }
            return this._Repository.GetGradeName(ids);
        }
    }
}
